<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>EPUB.js Spreads Example</title>

  <script src="./jszip@3.10.1.min.js"></script>
  <script src="./epubjs@0.3.88.min.js"></script>

  <link rel="stylesheet" type="text/css" href="./epub.css">

</head>
<body>
<!-- <div id="title"></div> -->
<select id="toc"></select>
<div id="viewer" class="spreads"></div>
<a id="prev" href="#prev" class="arrow">‹</a>
<a id="next" href="#next" class="arrow">›</a>

<script>
  // --- 你的原始代码 ---
  const params =
    URLSearchParams &&
    new URLSearchParams(document.location.search.substring(1))
  const url =
    params && params.get('url') && decodeURIComponent(params.get('url'))
  const currentSectionIndex =
    params && params.get('loc') ? params.get('loc') : undefined
  let blob = fetch(url).then((res) => res.blob())
  const book = ePub(
    blob.then((blob) => blob.arrayBuffer()),
    {
      restore: true,
      reload: true,
      spreads: true,
    },
  )
  const rendition = book.renderTo('viewer', {
    width: '100%',
    height: 600,
    spread: 'always',
  })

  rendition.display(currentSectionIndex)

  // 自动切换主题
  function applySystemTheme() {
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    document.documentElement.classList.toggle('dark', isDark);
  }

  applySystemTheme();

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    document.documentElement.classList.toggle('dark', e.matches);
  });

  book.ready.then(function() {

    rendition.themes.register("dark", {
      // 规则对象： '选择器': { 'css属性': '值' }
      "body": {
        "background": "#121212 !important",
        "color": "#e0e0e0 !important"
      },
      "a": {
        "color": "#8ab4f8 !important" // 优化暗黑模式下的链接颜色
      },
      "h1, h2, h3, h4, h5, h6": {
        "color": "#f1f1f1 !important" // 标题颜色
      }
    });

    if (document.documentElement.classList.contains('dark')) {
      rendition.themes.select("dark");
    }

    const next = document.getElementById('next')
    next.addEventListener('click', function(e) {
      book.package.metadata.direction === 'rtl' ? rendition.prev() : rendition.next()
      e.preventDefault()
    }, false)

    const prev = document.getElementById('prev')
    prev.addEventListener('click', function(e) {
      book.package.metadata.direction === 'rtl' ? rendition.next() : rendition.prev()
      e.preventDefault()
    }, false)

    const keyListener = function(e) {
      if ((e.keyCode || e.which) === 37) {
        book.package.metadata.direction === 'rtl' ? rendition.next() : rendition.prev()
      }
      if ((e.keyCode || e.which) === 39) {
        book.package.metadata.direction === 'rtl' ? rendition.prev() : rendition.next()
      }
    }

    rendition.on('keyup', keyListener)
    document.addEventListener('keyup', keyListener, false)

  })

  rendition.on('rendered', function(section) {
    const current = book.navigation && book.navigation.get(section.href)
    if (current) {
      const $select = document.getElementById('toc')
      const $selected = $select.querySelector('option[selected]')
      if ($selected) {
        $selected.removeAttribute('selected')
      }
      const $options = $select.querySelectorAll('option')
      for (let i = 0; i < $options.length; ++i) {
        let selected = $options[i].getAttribute('ref') === current.href
        if (selected) {
          $options[i].setAttribute('selected', '')
        }
      }
    }
  })

  rendition.on('relocated', function(location) {
    const next = book.package.metadata.direction === 'rtl' ? document.getElementById('prev') : document.getElementById('next')
    const prev = book.package.metadata.direction === 'rtl' ? document.getElementById('next') : document.getElementById('prev')
    if (location.atEnd) {
      next.style.visibility = 'hidden'
    } else {
      next.style.visibility = 'visible'
    }
    if (location.atStart) {
      prev.style.visibility = 'hidden'
    } else {
      prev.style.visibility = 'visible'
    }
  })

  rendition.on('layout', function(layout) {
    let viewer = document.getElementById('viewer')
    if (layout.spread) {
      viewer.classList.remove('single')
    } else {
      viewer.classList.add('single')
    }
  })

  window.addEventListener('unload', function() {
    this.book.destroy()
  })

  book.loaded.navigation.then(function(toc) {
    const $select = document.getElementById('toc'),
      docfrag = document.createDocumentFragment()
    toc.forEach(function(chapter) {
      const option = document.createElement('option')
      option.textContent = chapter.label
      option.setAttribute('ref', chapter.href)
      docfrag.appendChild(option)
    })
    $select.appendChild(docfrag)
    $select.onchange = function() {
      const index = $select.selectedIndex,
        url = $select.options[index].getAttribute('ref')
      rendition.display(url)
      return false
    }
  })

</script>

</body>
</html>
